package com.changgou.seckill.timer;

import com.changgou.entity.DateUtil;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsPushTask {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void loadGoodsPushRedis() {
        List<Date> dateMenus = DateUtil.getDateMenus();

        for (Date dateMenu : dateMenus) {
            String timespace ="SeckillGoods_"+ DateUtil.date2Str(dateMenu);

            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", "1");
            criteria.andGreaterThan("stockCount", 0);
            criteria.andGreaterThanOrEqualTo("startTime", "2019-07-07");
        //    criteria.andGreaterThanOrEqualTo("startTime", dateMenu);
     //       criteria.andLessThan("endTime", DateUtil.addDateHour(dateMenu, 2));

            Set keys = redisTemplate.boundHashOps(timespace).keys();
            if (keys != null && keys.size() > 0) {
                criteria.andNotIn("id", keys);
            }

            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);

            seckillGoods.forEach(item->{
                System.out.println("商品id:"+item.getId()+"-------"+timespace);
                redisTemplate.boundHashOps(timespace).put(item.getId(), item);
//
//                redisTemplate.boundListOps("SeckillGoodsCountList_" + item.getId())
//                        .leftPushAll(putAllIds(item.getStockCount(), item.getId()));
            });

        }
    }

    public Long[] putAllIds(Integer num,Long id) {
        Long[] ids = new Long[num];
        for (int i = 0; i <ids.length ; i++) {
            ids[i] = id;
        }
        return ids;
    }
}
